package com.woniuxy.microsystemuapserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.slsupermarket.common.res.ResponseMsg;
import com.slsupermarket.common.util.JWTUtil;
import com.woniuxy.microsystemuapserver.bean.PageResult;
import com.woniuxy.microsystemuapserver.bean.ResultMsg;
import com.woniuxy.microsystemuapserver.bean.UserBean;
import com.woniuxy.microsystemuapserver.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: huhenggg
 * @Date: 2021/1/25 0025 下午 2:18
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Resource
    private UserService userServiceImpl;

    /**
     * 登录方法
     * @param loginName
     * @param password
     * @return
     */
    @PostMapping(value = "/login",produces = MediaType.APPLICATION_JSON_VALUE)
    public String login(String loginName,String password){

        System.out.println(loginName +"用户名");
        System.out.println(password +"密码");

        //取得当前的主体对象（就指登录人）
        Subject subject = SecurityUtils.getSubject();
        //判断实体对象，是否已经认证过
        if(!subject.isAuthenticated()){
            UsernamePasswordToken shiroToken = new UsernamePasswordToken(loginName,password);

            try {
                subject.login(shiroToken);
                System.out.println("认证 成功");
            } catch (UnknownAccountException e) {
                System.out.println("账号不存在");
                return JSONObject.toJSONString(ResponseMsg.builder().
                        code(10002).msg("登录名或密码错误").build());
            } catch (IncorrectCredentialsException e) {
                System.out.println("密码错误");
                return JSONObject.toJSONString(ResponseMsg.builder().
                        code(10002).msg("登录名或密码错误").build());
            } catch (Exception e) {
                System.out.println("其他异常");
            }
        }
        //如果认证通过了，就直接产生JWT令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put("loginName",loginName);
        //调用业务层将用户名放入到载荷中
        UserBean userBean = userServiceImpl.login(loginName);
        claims.put("userid",userBean.getId().toString());
        String token = JWTUtil.createToken(claims);
        //查询当前用户的角色权限
        UserBean roleAndPermission = userServiceImpl.findRoleAndPermission(loginName);
        List list = new ArrayList<Object>();
        list.add(token);
        list.add(roleAndPermission);

        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("登录成功").data(list).build());

        //并将用户信息放入到redis中
    }

    /**
     * 查询用户所有的角色、权限信息、能看的菜单栏
     * @return
     */
    @GetMapping("/allUseInfo")
    public UserBean findAll(String userAccount, HttpServletRequest  request) {

        String token = request.getHeader("authentication");
        System.out.println(token);
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JWTUtil.SECURITY)).build();
        DecodedJWT verify = verifier.verify(token);
        String id = verify.getClaim("userid").asString();
        System.out.println(id +"当前用户的id+++++++");

        return userServiceImpl.findRoleAndPermission("superadmin");
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @param userBean
     * @return
     */
    @GetMapping("/findByPage")
    PageResult<List<UserBean>> findByPage(int page, int size, UserBean userBean) {

        //此处封对象


        PageResult<List<UserBean>> result = userServiceImpl.findByPage(page, size, userBean);
        return result;

    }

    /**
     * 修改用户
     * @param userBean
     * @return
     */
    @GetMapping("/updateUserBean")
    public ResultMsg updateUserBean(UserBean userBean) {

        //此处封对象

        userServiceImpl.updateUserBean(userBean);

        return null;

    }


    /**
     * 新增用户  此处业务是老板新增员工账号
     * @param userBean
     * @return
     */
    @PostMapping("/add")
    public ResultMsg addUser(UserBean userBean) {

        //此处封对象

        userServiceImpl.addUser(userBean);

        return null;
    }

    /**
     * 通过userid查询用户的个人信息  这里主要是查询老板的信息
     * @return
     */
    @GetMapping("/findInfo")
    public Map userInfo(HttpServletRequest  request) {
        ResultMsg resultMsg = new ResultMsg();
        String token = request.getHeader("authentication");
        System.out.println(token);
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JWTUtil.SECURITY)).build();
        DecodedJWT verify = verifier.verify(token);
        String id = verify.getClaim("userid").asString();
        System.out.println(id +"当前用户的id+++++++userInfo");
        Long userid = Long.getLong(id);
        Map aUser = userServiceImpl.findAUser(1L);
        System.out.println(aUser);
        return aUser;
    }


    /**
     * 查询老板对应的所有员工
     * @param page
     * @param size
     * @param userBean
     * @return
     */
    @GetMapping("/allBossUserInfo")
    public PageResult<List<UserBean>> find(int page, int size,UserBean userBean) {
        PageResult pageResult = new PageResult();
        userServiceImpl.findByPage(size,page,userBean);
        return pageResult;
    }
}
